package com.sptpc.demo1.service.impl;

import com.sptpc.demo1.model.Category;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.repository.CategoryRepository;
import com.sptpc.demo1.repository.DrinkRepository;
import com.sptpc.demo1.service.IDrinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class DrinkJpaService implements IDrinkService {
    @Autowired
    private DrinkRepository drinkRepository;

    @Autowired
    private CategoryRepository categoryRepository;
    public List<Drink> getAllDrinks(PageRequest pageRequest){
        return drinkRepository.findAll();
    }


    @Override
    public void addnewDrink(Drink drink, Integer categoryId) {
        //1.通过categoryId查询category
        Category category=categoryRepository.findById(categoryId).orElse(null);
        //2.将category设置给Drink
        drink.setCategory(category);
        drinkRepository.save(drink);
    }

    @Override
    public Drink getDrinkById(Integer id) {
        Optional<Drink> optional= drinkRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public void updateDrink(Drink drink) {
        drinkRepository.save(drink);
    }

    @Override
    public void deleteDrinkById(Integer id) {

        drinkRepository.deleteById(id);
    }

}
